package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyCenterUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.ProgessTools;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.adapter.AddressAdapter;
import com.mlz.mlzmall.ui.dialog.ReuestDialog;
import com.mlz.mlzmall.ui.model.AddressListBean;
import com.mlz.mlzmall.ui.model.AddressListBean.DataBean;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import com.mlz.mlzmall.ui.model.AddressListBean.DataBean.ListBean;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.AppManager;
import com.mlz.mlzmall.ui.utils.util.LogUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by yhf on 2016/5/18.
 */
public class ReceiveAddress extends VolleyBaseActivity {

    private static final String TGA = "ReceiveAddress";
    private Button btnAddNewAddress;//添加地址按钮
    private RelativeLayout rlNoAddress;//没有地址
    private List<ListBean> list;//数据源（地址）

    private ListView lvAddress;//地址的listView
    private AddressAdapter adapter;//收货地址的适配器
    private String str="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.receive_address);//跳转到收货地址界面
        setViewContent();
        initView();
    }
    private void setViewContent() {
        TopTitleView loginTopTitle = (TopTitleView) findViewById(R.id.login_top_title);
        loginTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        loginTopTitle.setTitleButtonContent("收货地址", null, null);
        loginTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                ReceiveAddress.this.overridePendingTransition(R.anim.right_in,R.anim.right_out);
            }
        });
        str = getIntent().getStringExtra(ConfigInfo.ACT_STATUS);
        Log.i(TGA, "传递的标记：" + str);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAddress();//请求地址数据
    }

    /**
     * 初始化
     */
    private void initView() {
        lvAddress = (ListView) findViewById(R.id.lv_address);
        btnAddNewAddress = (Button) findViewById(R.id.btn_add_new_address);
        rlNoAddress = (RelativeLayout) findViewById(R.id.rl_no_address);
        btnAddNewAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReceiveAddress.this, AddNewAddress.class);
                startActivityForResult(intent, 100);
                ReceiveAddress.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
            }
        });
    }

    private void initList(ArrayList list2) {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        } else {
            List<ListBean> data = (List<ListBean>) list2.get(0);
            adapter = new AddressAdapter(this, data, R.layout.address_item);
            lvAddress.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        lvAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final Intent intent = new Intent();
                if (str.equals("1001")) {
                    intent.putExtra("FullName", list.get(position).getFullname());
                    intent.putExtra("Telephone", list.get(position).getShippingTelephone());
                    intent.putExtra("Address", list.get(position).getAddress());
                    intent.putExtra("AddressId", list.get(position).getAddressId());
                    intent.putExtra("RegionCode", list.get(position).getRegionCode());
                    intent.putExtra("DefaultAddress", list.get(position).isDefaultAddress());
                    intent.putExtra("Postcode", list.get(position).getPostcode());//传的参数看这里
                    setResult(RESULT_OK, intent);
                } else if (str.equals("1002")) {
                    intent.setClass(ReceiveAddress.this, ConfirmExchangeActivity.class);
                    intent.putExtra("FullName", list.get(position).getFullname());
                    intent.putExtra("Telephone", list.get(position).getShippingTelephone());
                    intent.putExtra("Address", list.get(position).getAddress());
                    intent.putExtra("AddressId", list.get(position).getAddressId());
                    intent.putExtra("RegionCode", list.get(position).getRegionCode());
                    intent.putExtra("DefaultAddress", list.get(position).isDefaultAddress());
                    intent.putExtra("Postcode", list.get(position).getPostcode());//传的参数看这里
                    startActivity(intent);
                } else if ("1003".equals(str)) {
                    final String Warehouse = getIntent().getStringExtra("warehouse");
                    executeRequest(RequestUtils.POSTWarehouse(mContext, Warehouse, ReceiveAddress.this.list.get(position).getAddressId(), new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            Log.i(tag, "返回的数据" + jsonObject.toString());
                            ProgessTools.closeProgressDialog();
                            try {
                                JSONObject json = new JSONObject(jsonObject.toString());
                                int status = json.getInt("status");
                                String msg = json.getString("msg");
                                if (0 == status) {
                                    MyCenterUtils.ToastText(msg);
                                    intent.putExtra("warehouse", Warehouse);
                                    setResult(201, intent);
                                    finish();
                                }
                                if (0 != status) {
                                    MyCenterUtils.ToastText(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }));
                } else {
                    intent.setClass(ReceiveAddress.this, ChangeAddress.class);
                    intent.putExtra("FullName", list.get(position).getFullname());
                    intent.putExtra("Telephone", list.get(position).getShippingTelephone());
                    intent.putExtra("Address", list.get(position).getAddress());
                    intent.putExtra("AddressId", list.get(position).getAddressId());
                    intent.putExtra("RegionCode", list.get(position).getRegionCode());
                    intent.putExtra("DefaultAddress", list.get(position).isDefaultAddress());
                    intent.putExtra("Postcode", list.get(position).getPostcode());//传的参数看这里
                    startActivity(intent);
                }
                ReceiveAddress.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
            }
        });
    }



    /**
     * 请求地址的数据
     */
    private void getAddress() {
        ReuestDialog.showProgressDialog(ReceiveAddress.this);//显示加载框
        list = new ArrayList<ListBean>();
        tag = "rGet";
        Map<String, String> paraml = new HashMap<>();
        paraml.put("pageNum", "1");
        paraml.put("pageSize", "100");
        JSONObject jsonObject = new JSONObject(paraml);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.ADDRESS.LIST, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                ReuestDialog.dissmissProgressDialog();
                Log.e(tag, jsonObject.toString());
                Gson gson = new Gson();
                AddressListBean addressInfo = gson.fromJson(jsonObject.toString(), AddressListBean.class);
                DataBean db = addressInfo.getData();
                if (db.getTotal() == 0) {
                    rlNoAddress.setVisibility(View.VISIBLE);
                    lvAddress.setVisibility(View.GONE);
                } else {
                    rlNoAddress.setVisibility(View.GONE);
                    lvAddress.setVisibility(View.VISIBLE);
                    LogUtils.d("刷新！！！！");
                    /*******************把设置了默认地址的数据置顶******************************/
                    // 取到的地址信息逐条添加到集合中
                    Iterator<ListBean> it = db.getList().iterator();
                    // 先清除数据
                    list.clear();
                    while (it.hasNext()) {
                        ListBean i = it.next();
                        if (i.isDefaultAddress()) {
                            list.add(0, i);
                        } else {
                            list.add(i);
                        }
                    }
                    ArrayList list2 = new ArrayList();
                    list2.add(list);
                    /***************************************************/
                    adapter = null;
                    initList(list2);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ReuestDialog.dissmissProgressDialog();//显示加载框
                showToast(volleyError.getMessage());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY +  sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };
        //设置请求标签
        jsonRequest.setTag(tag);
        //将该请求添加到请求队列
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }

}
